package com.yc.testupload.controller;

import com.yc.testupload.dao.UserDAO;
import com.yc.testupload.model.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import com.yc.testupload.dao.UserDAO;
import com.yc.testupload.model.User;

@WebServlet(name = "registerServlet", value = "/register")
public class RegisterServlet extends HttpServlet {

    private static final Logger logger = LogManager.getLogger(RegisterServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        
        // 获取请求参数
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        
        logger.info("接收到注册请求，手机号: {}, 邮箱: {}", phone, email);
        
        try {
            // 验证参数不为空
            if (phone == null || phone.isEmpty() || email == null || email.isEmpty() || 
                password == null || password.isEmpty() || confirmPassword == null || confirmPassword.isEmpty()) {
                logger.warn("注册失败：参数不完整");
                out.write("{\"code\":1,\"message\":\"参数不完整，请填写所有必填项\"}");
                return;
            }
            
            // 验证手机号格式
            if (!phone.matches("^1[3-9]\\d{9}$")) {
                logger.warn("注册失败：手机号格式不正确: {}", phone);
                out.write("{\"code\":1,\"message\":\"请输入有效的手机号码\"}");
                return;
            }
            
            // 验证邮箱格式
            if (!email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$")) {
                logger.warn("注册失败：邮箱格式不正确: {}", email);
                out.write("{\"code\":1,\"message\":\"请输入有效的邮箱地址\"}");
                return;
            }
            
            // 验证密码长度
            if (password.length() < 6) {
                logger.warn("注册失败：密码长度不足");
                out.write("{\"code\":1,\"message\":\"密码长度不能少于6位\"}");
                return;
            }
            
            // 验证两次输入的密码是否一致
            if (!password.equals(confirmPassword)) {
                logger.warn("注册失败：两次输入的密码不一致");
                out.write("{\"code\":1,\"message\":\"两次输入的密码不一致，请重新输入\"}");
                return;
            }
            
            // 使用UserDAO进行数据库操作
            UserDAO userDAO = new UserDAO();
            
            // 检查用户名(手机号)是否已被注册
            if (userDAO.checkUsernameExists(phone)) {
                logger.warn("注册失败：手机号已被注册: {}", phone);
                out.write("{\"code\":1,\"message\":\"该手机号已被注册\"}");
                return;
            }
            
            // 检查邮箱是否已被注册
            if (userDAO.checkEmailExists(email)) {
                logger.warn("注册失败：邮箱已被注册: {}", email);
                out.write("{\"code\":1,\"message\":\"该邮箱已被注册\"}");
                return;
            }
            
            // 生成盐值和加密密码
            String salt = userDAO.generateSalt();
            String hashedPassword = userDAO.hashPassword(password, salt);
            
            // 创建用户对象
            User user = new User();
            user.setUserName(phone); // 使用手机号作为用户名
            user.setUserEmail(email);
            user.setUserPass(hashedPassword);
            user.setUserSalt(salt);
            
            // 保存用户信息到数据库
            boolean success = userDAO.createUser(user);
            
            if (success) {
                logger.info("用户注册成功，手机号: {}, 邮箱: {}", phone, email);
                out.write(String.format("{\"code\":0,\"message\":\"注册成功\",\"data\":{\"phone\":\"%s\",\"email\":\"%s\"}}", phone, email));
            } else {
                logger.error("用户注册失败，数据库保存失败");
                out.write("{\"code\":1,\"message\":\"注册失败，请稍后重试\"}");
            }
        } catch (Exception e) {
            logger.error("注册过程中发生错误: {}", e.getMessage(), e);
            out.write("{\"code\":500,\"message\":\"系统错误，请稍后重试\"}");
        } finally {
            out.flush();
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 重定向到注册页面
        response.sendRedirect("/register.html");
    }
}